<?php
require_once "config.php";
require_once "includeFunctions.php";
require_once "filter.php";
require_once "simplepie/simplepie.inc";
require_once "GoogleAPI.php";
require_once "Connection.php";
session_start();

if(isset($_SESSION['LOGIN_INFO']['id'])){
	/*
	 * 有登入就抓自已設定的
	 * 沒登入就抓default的 from config
	 */
	
	$conn = new Connection();
	
	$sub_category = $conn->fetchSubCategory($_SESSION['LOGIN_INFO']['id']);
	$sub_category = urldecode($sub_category);
	$sub_category = json_decode($sub_category,true);
	
}


$googleAPI = new GoogleAPI();

if(!isset($sub_category[$_POST['category']][$_POST['key']]['url'])){
	/*
	 * 分類為空
	 */ 
	echo json_encode(array('status'=>false,'error_code'=>1,'msg'=>'目前沒有訂閱'));
	exit;
}
elseif(!isset($sub_category[$_POST['category']][$_POST['key']]['url']) && !empty($sub_category[0][0])){
	/*
	 * 表示這個subscription 不存在
	 */ 
	echo json_encode(array('status'=>false,'error_code'=>0,'msg'=>''));
	exit;
}
else{
	$url = $sub_category[$_POST['category']][$_POST['key']]['url'];
	$selected_category = $_POST['category'];
	$selected_key = $_POST['key'];
	$more = $_POST['more'];
}




$feed = new SimplePie();

$feed->set_feed_url($url);

//$feed->set_input_encoding(false);
//$feed->set_output_encoding('big5');

$feed->force_feed(TRUE);
$feed->init();

// Make sure the page is being served with the UTF-8 headers.
$feed->handle_content_type();
$max = $feed->get_item_quantity();

$length = 8;//一次顯示8則
$start = $more*$length;//start index

$more++;

//$expand = new ExpandWord();
$counter = $start;

$msg = '';
foreach($feed->get_items($start,$length) as $item){
	//error_log($item->get_permalink());
	$msg .= '<div class="gradient">';
	$msg .= '<h1><a href="'.$item->get_permalink().'" target="_blank">'.urldecode($item->get_title()).'</a></h1>';
	
	$msg .= '<p class="block small gold">'.$item->get_date('j M Y  g:i a').'</p>';
	$msg .= '<p>'.urldecode($item->get_content()).'</p>';
	$msg .= '<blockquote class="exclamation">';		
		$msg .= '<div id="keyword_pool'.$counter.'" class="keyword_pool">';
			$msg .= '<p id="loading_img'.$counter.'"><img src="styles/images/ui-anim_basic_16x16.gif"/></p>';
			$msg .= '<p id="keyword_pool'.$counter.'_string" style="display:none">'.urlencode($item->get_title()).'</p>';
		$msg .= '</div>';
	$msg .= '</blockquote>';
	$msg .= '</div>';	
	$counter++;
}



if(($start+$length) < $max){	
	$msg .= '<div id="get_more" class="alignCenter"><span class="green" style="cursor: pointer; cursor: hand;" onclick="getRSSByCategory(\''.$selected_category.'\',\''.$selected_key.'\',\''.false.'\',\''.$more.'\')">看更多</span></div>';
}
else{
	$msg .= '<div id="get_more" class="alignCenter">無更多資料</div>';
}

echo json_encode(array('status'=>true,'msg'=>$msg));

?>